﻿//------------------------------------------------------------------------------
// ╭─────────────────────────────╮
// │ ╭─╮     ╭─╮              TM │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// │ │ │     │ │                 │                                           ☺  
// │ │ ╰───╮ │ │ ╭─────╮ ╭─────╮ │     Name:Wedn.Net User管理类拓展代码  ♮ ♪ ♩
// │ │ ╭─╮ │ │ │ │ ╭─╮ │ │ ╭─╮ │ │                                    ♫ ♭      
// │ │ ╰─╯ │ │ │ │ ╰─╯ │ │ ╰─╯ │ │     Author:iceStone               ♬ ♪       
// │ └─────╯ └─╯ ╰─────╯ ╰───╮ │ │     Chinese:汪磊                              
// │                     ┌───╯ │ │                                              
// │                     ╰─────╯ │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// ╰─────────────────────────────╯                                              
//------------------------------------------------------------------------------
using System.Linq;
using Wedn.Net.Common;
using Wedn.Net.Model;
using Wedn.Net.Utility;

namespace Wedn.Net.BLL
{
    /// <summary>
    /// User管理类 UserManager
    /// </summary>
    public partial class UserManager
    {
        #region User常用业务

        /// <summary>
        /// OAuth用户登录
        /// </summary>
        /// <param name="uid">用户登录名</param>
        /// <param name="user">当前用户</param>
        /// <returns>登录结果</returns>
        public LoginResult OAuthLogin(string uid, out User user)
        {
            user = Select(u => u.Login == uid.ToLower()).FirstOrDefault();
            return user == null
                       ? LoginResult.OAuthFail
                       : LoginResult.OAuthSuccess;
        }

        /// <summary>
        /// 校验用户登录
        /// </summary>
        /// <param name="uid">用户登录名</param>
        /// <param name="pwd">用户密码</param>
        /// <param name="user">当前用户</param>
        /// <returns>登录结果</returns>
        public LoginResult Login(string uid, string pwd, out User user)
        {
            return Login(uid, pwd, out user, false);
        }

        /// <summary>
        /// 校验用户登录
        /// </summary>
        /// <param name="uid">用户登录名</param>
        /// <param name="pwd">用户密码</param>
        /// <param name="user">当前用户</param>
        /// <param name="isFromCookie">登陆信息时候来自Cookie</param>
        /// <returns>登录结果</returns>
        public LoginResult Login(string uid, string pwd, out User user, bool isFromCookie)
        {
            user = Select(u => u.Login == uid.ToLower()).FirstOrDefault();
            return user == null
                       ? LoginResult.NonExistent
                       : (user.Password == (isFromCookie ? pwd : StringHelper.Encrypt(pwd))
                              ? LoginResult.Success
                              : (user.Status == 1 ? LoginResult.Awaiting : LoginResult.PasswordError));
        }

        /// <summary>
        /// 获取一个用户的加密信息字符串
        /// </summary>
        /// <param name="user">用户实体</param>
        /// <returns>加密后的字符串</returns>
        public string GetEncryptUserInfo(User user)
        {
            var temp = string.Format("uid={0}&ulogin={1}&upwd={2}", user.Id, user.Login, user.Password);
            return temp.EncryptStr();//StringHelper.EncryptCookie(temp);
        }
        /// <summary>
        /// 根据加密后的cookie解密出用户实体部分信息, 返回用户实体
        /// </summary>
        /// <param name="cookie">要解密的cookie</param>
        /// <returns>返回用户实体</returns>
        public User GetDecryptUserInfo(string cookie)
        {
            string temp;
            try
            {
                temp = cookie.DecryptStr();//StringHelper.DecryptCookie(cookie);
            }
            catch
            {
                return null;
            }
            var infos = temp.Split('&');
            return new User
            {
                Id = int.Parse(infos[0].Split('=')[1]),
                Login = infos[1].Split('=')[1],
                Password = infos[2].Split('=')[1]
            };
        }

        /// <summary>
        /// 校验用户是否已经登录
        /// </summary>
        public bool CheckLogin()
        {
            var currentUser = SessionHelper.GetSession<User>("CurrentUser");
            //User CurrentUser = context.Session["CurrentUser"] as User;
            if (currentUser != null)
                return true;
            return CookieLogin();
        }

        /// <summary>
        /// 校验cookie登录
        /// </summary>
        /// <returns>是否登陆成功</returns>
        public bool CookieLogin()
        {
            //HttpCookie cookie = context.Request.Cookies[Config.SitePrefix + "URM"];
            string cookie = CookieHelper.GetCookie("URM");
            if (!string.IsNullOrEmpty(cookie))
            {
                //UserManager userManager = new UserManager();
                var cookieUser = GetDecryptUserInfo(cookie);
                if (cookieUser != null)
                {
                    User currentUser;
                    var res = Login(cookieUser.Login, cookieUser.Password, out currentUser, true);
                    if (res == LoginResult.Success)
                    {
                        //审核通过
                        //if (HttpContext.Current.Session["CurrentUser"] == null)
                        //    HttpContext.Current.Session["CurrentUser"] = currentUser;
                        SessionHelper.SetSession("CurrentUser", currentUser);
                        //换Cache模拟Session
                        //CacheHelper.SetCache(
                        return true;
                    }
                }
                else
                {
                    //密码被修改了.清除cookie
                    //context.Response.Cookies[Config.SitePrefix + "URM"].Expires = DateTime.Now.AddDays(-1);
                    CookieHelper.RemoveCookie("URM");
                }
            }
            return false;
        }
        #endregion

        public override IQueryable<User> Select(System.Linq.Expressions.Expression<System.Func<User, bool>> where)
        {
            IQueryable<User> res = CacheHelper.GetCache<IQueryable<User>>("UserList");
            if (res == null)
            {
                res = base.Select(u => true);
                CacheHelper.SetCache("UserList", res);
            }
            return res.Where(where);
        }
    }
}
